/**
 * @description editor 插件，重写 editor API
 */
import { SlateEditor, SlateTransforms, SlatePoint, SlateNode, DomEditor } from '@wangeditor/editor';
import { PAGEPAD_TYPE } from './index';
console.log("🚀 ~ PAGEPAD_TYPE:", PAGEPAD_TYPE);

function withPagePad(editor) {
  const { insertBreak, insertText } = editor;
  const newEditor = editor;

  // 重写 insertBreak - 换行时插入 p
  newEditor.insertBreak = () => {
    const { selection } = newEditor;
    if (selection == null) {
      console.log("Selection is null, calling original insertBreak");
      return insertBreak();
    }

    const [nodeEntry] = SlateEditor.nodes(editor, {
      match: n => DomEditor.checkNodeType(n, 'pagePad'),
      universal: true
    });
    if (!nodeEntry) {
      console.log("No pagePad node found, calling original insertBreak");
      return insertBreak();
    }

    const quoteElem = nodeEntry[0];
    const quotePath = DomEditor.findPath(editor, quoteElem);
    const quoteEndLocation = SlateEditor.end(editor, quotePath);

    if (!SlatePoint.equals(quoteEndLocation, selection.focus)) {
      console.log("Cursor is not at the end of pagePad node, calling original insertBreak");
      return insertBreak();
    }

    const str = SlateNode.string(quoteElem);
    if (!str || str.slice(-1) !== '\n') {
      console.log("Last character is not \\n, calling original insertBreak");
      return insertBreak();
    }

    // 光标位于 元素的 最后
    console.log("Cursor is at the end of pagePad node and last character is \\n");

    editor.deleteBackward('character'); // 删除最后一个 \n

    // 则插入一个 paragraph
    const p = { type: 'paragraph', children: [{ text: '' }] };
    SlateTransforms.insertNodes(newEditor, p, { mode: 'highest' });
    console.log("Inserted paragraph node");
  };

  return newEditor;
}

export default withPagePad;